package com.bsy.videostation.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import coil.transform.RoundedCornersTransformation
import com.bsy.framework.base.BaseMvvmFragment
import com.bsy.framework.ext.data
import com.bsy.framework.ext.onClick
import com.bsy.framework.helper.AppHelper
import com.bsy.framework.utils.dpToPx
import com.bsy.videostation.adapter.HomeMainAdapter
import com.bsy.videostation.adapter.lisener.OnItemClickListener
import com.bsy.videostation.manager.UserManager
import com.bsy.videostation.model.VideoEntity
import com.bsy.videostation.ui.activity.WebViewActivity
import com.bsy.videostation.view_type.HomeViewType
import com.bsy.videostation.viewmodel.MainViewModel
import com.dg.videostation.R
import com.dg.videostation.databinding.FragmentHomeBinding
import me.jessyan.autosize.AutoSize

/**
 * Created by Lucy on 2024/2/21.
 * Copyright
 * 描述 :
 */
class HomeFragment : BaseMvvmFragment<FragmentHomeBinding, MainViewModel>(), OnItemClickListener<VideoEntity> {
    private val homeAdapter: HomeMainAdapter by lazy {
        HomeMainAdapter()
    }

    //是否打开新页面
    private var isOpenNewPage = false
    private val headerView: View by lazy {
        LayoutInflater.from(context).inflate(R.layout.item_home_header, mBinding?.rvContent, false)
    }

    override fun initViewModel() {
        mViewModel = AppHelper.getApplicationViewModel(MainViewModel::class.java)
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        initRv()
    }

    override fun initData() {
        mViewModel.getVideoListById {
            if (it)
                showLoading()
            else
                dismissLoading()
        }
    }

    private fun initRv() {
        mBinding?.rvContent?.apply {
            this.layoutManager =
                LinearLayoutManager(context, RecyclerView.HORIZONTAL, false).apply {
                    initialPrefetchItemCount = 1
                }
            setHasFixedSize(true)
        }
    }

    override fun initObserver() {
        mViewModel.videoList.observe(this) {
            if (mBinding?.rvContent?.adapter == null) {
                mBinding?.rvContent?.adapter = homeAdapter
                homeAdapter.addHeaderView(headerView, -1, RecyclerView.HORIZONTAL)
            }
            homeAdapter.setList(it)
        }
        mViewModel.headerData.observe(viewLifecycleOwner) {
            it?.let {
                setHeaderData(it)
            }
        }
        mViewModel.homeScrollToFirstPosition.observe(viewLifecycleOwner) {
            if (!isOpenNewPage && it == 0)
                mBinding?.rvContent?.scrollToPosition(0)
            else
                isOpenNewPage = false
        }
        mViewModel.panel.observe(viewLifecycleOwner) {
            mViewModel.fetchAllVideos(it)
        }
    }

    override fun initListener() {
        homeAdapter.setCustomOnItemClickListener(this)
    }

    //设置RecycleView头部
    private fun setHeaderData(videoInfo: VideoEntity) {
        val headItem = headerView.findViewById<ImageView>(R.id.iv_cover)
        headItem.load(videoInfo.cover) {
            transformations(RoundedCornersTransformation(dpToPx(10F)))
        }
        headerView.findViewById<ImageView>(R.id.iv_app).load(videoInfo.sourceIcon) {
            transformations(RoundedCornersTransformation(dpToPx(10F)))
        }
        headerView.findViewById<TextView>(R.id.tv_title).apply {
            this.isVisible = videoInfo.isVertical.data()
            this.text = videoInfo.title.data()
        }
        //头部Item
        headItem.onClick {
            toDetailPage(videoInfo)
        }
        headerView.findViewById<ConstraintLayout>(R.id.view_recommend).onClick {
            mViewModel.categorySelectId = videoInfo.id.data()
            mViewModel.historyEvent.value = HomeViewType.RECOMMEND_PAGE.value
        }
        headerView.findViewById<ConstraintLayout>(R.id.view_history).onClick {
            mViewModel.historyEvent.value = HomeViewType.HISTORY_PAGE.value
        }

    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        AutoSize.autoConvertDensity(activity, 768F, false)
        return getContentView(inflater, container)
    }

    companion object {
        fun newInstance() = HomeFragment()
    }

    override fun onClick(position: Int, item: VideoEntity) {
        toDetailPage(item)
    }

    /**
     * 去视频详情页
     *
     * @param videoInfo 视屏信息
     */
    private fun toDetailPage(videoInfo: VideoEntity) {
        if (videoInfo.detail.isNullOrEmpty()) {
            showToast("No play address found")
            return
        }
        isOpenNewPage = true
        videoInfo.time = System.currentTimeMillis()
        UserManager().addHistory(videoInfo)
        val intent = Intent(context ?: requireContext(), WebViewActivity::class.java)
        val bundle = Bundle().apply {
            putString("url", videoInfo.detail)
        }
        intent.putExtras(bundle)
        startActivity(intent)
    }

}